package com.example.cheapshark.mobile;

import java.math.BigDecimal;
import java.math.RoundingMode;

import android.content.Context;
import android.graphics.Paint;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class GameDealAdapter extends ArrayAdapter<GameDeal> {
	private final Context context;
	private final GameDeal[] deals;
	private final int layout;

	public GameDealAdapter(Context context, int layout, GameDeal[] deals) {
		super(context, layout, deals);
		this.context = context;
		this.deals = deals;
		this.layout = layout;
	}

	public View getView(int position, View convertView, ViewGroup parent) {
		LayoutInflater inflater = (LayoutInflater) context
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View rowView = inflater.inflate(layout, parent, false);
		int actualPosition = position % CSMobileApplication.getNumberOfPages();
		setData(deals[actualPosition], rowView);
		return rowView;
	}

	public void setData(GameDeal deal, View rowView) {
		if (deal != null) {
			TextView title = (TextView) rowView.findViewById(R.id.title);
			ImageView thumb = (ImageView) rowView.findViewById(R.id.thumb);
			TextView normalPrice = (TextView) rowView
					.findViewById(R.id.normalPrice);
			normalPrice.setPaintFlags(normalPrice.getPaintFlags()
					| Paint.STRIKE_THRU_TEXT_FLAG);
			TextView salePrice = (TextView) rowView
					.findViewById(R.id.salePrice);
			TextView percentOff = (TextView) rowView
					.findViewById(R.id.percentOff);
			thumb.setImageBitmap(deal.getThumb());
			title.setText(deal.getTitle());
			normalPrice.setText(deal.getNormalPrice().toString());
			salePrice.setText(deal.getSalePrice().toString());
			int percentOffVal = GetPercentOff(deal.getNormalPrice(),
					deal.getSalePrice());
			percentOff.setText(Integer.toString(percentOffVal) + "%");
		} else {
			Log.w("Game Deal Adapter", "deal blank (null)");
		}
	}

	private static int GetPercentOff(BigDecimal normalPrice,
			BigDecimal salePrice) {

		BigDecimal divResult = salePrice
				.divide(normalPrice, 2, RoundingMode.UP);
		return (int) ((1 - divResult.doubleValue()) * -100);
	}
}
